<?php
$specialId = Yii::app()->request->getParam('id');

$parentCaption = BUtils::T('offers_lbl');
$caption = empty($specialId) ? BUtils::T('create_offer_lbl') : BUtils::T('edit_offer_lbl');
$this->pageTitle = $caption;

$this->breadcrumbs = array(
	$parentCaption => array('index'),
	$caption,
);

//set offer picture
$url_thumb_default = Yii::app()->baseUrl . '/img/default_special_thumb.png';
$url_picture_default = Yii::app()->baseUrl . '/img/default_special_picture.png';
if (!empty($model->url_picture)) {
	$url_thumb = BUtils::GetOfferThumbUrl($model->url_picture);
	$url_picture = BUtils::GetOfferPictureUrl(str_replace('thumb_', '', $model->url_picture));
} else {
	$url_thumb = $url_thumb_default;
	$url_picture = $url_picture_default;
}

//define array
$aWeekDays = BUtils::WeekDayKeys(7, true);
$a24Hours = BUtils::AllHour24();

$add_hours_btn = BUtils::T('add_hours_btn');
$delete_btn = BUtils::T('delete_btn');
$hours_list_op = MerchantObject::HtmlOfferHoursForm($offer_hours, $aWeekDays, $a24Hours);
$hours_list = MerchantObject::HtmlOfferHours($offer_hours, $aWeekDays, $a24Hours);

//set day string
$week_string = BUtils::GetWeekdays($model->week_days, $aWeekDays);
$range_date = BUtils::GetRecentDayName($model->week_days, $week_string, false, $model->start_hour);
$range_time = BUtils::GetHourRangeFormat($model->start_hour, $model->end_hour, $model->show_hours);

//set price, discount or highlight
$highlight = $del_price = '';
if (!empty($model->price)) {
	$highlight = MerchantObject::formatPrice($model->price);
	if (!empty($model->value)) {
		$del_price = '<span class="oldprice label">€'.$model->value.'</span>';
	}
} elseif (!empty($model->discount)) {
	$highlight = MerchantObject::formatDiscount($model->discount);
}

//discount customized
if (!empty($model->discount)) $discount_percent = sprintf('%d', $model->discount * 100);
else $discount_percent = '';

//address
$biz_address = '';
if (!empty($r['address'])) {
	$biz_address = $r['address'];
	if (!empty($r['biz_area'])) $biz_address .= '<br />' . $r['biz_area'];
	if (!empty($r['postcode'])) $biz_address .= '<br />' . $r['postcode'] . ' ' . $r['city'];
}

//how to use tips
$using_show_icon = '<img src="'.Yii::app()->baseUrl.'/img/icons/using_show.png" alt="" />';
$using_show_msg = BUtils::T('special_using_show_lbl');
$using_click_icon = '<img src="'.Yii::app()->baseUrl.'/img/icons/using_show.png" alt="" />';
$using_click_msg = BUtils::T('special_using_click_lbl');
$using_scan_icon = '<img src="'.Yii::app()->baseUrl.'/img/icons/using_scan.png" alt="" />';
$using_scan_msg = BUtils::T('special_using_scan_lbl');
if ($model->redeem_type == 2) {
	$using_show_class = '';
	$using_click_class = 'none';
	$using_scan_class = 'none';
	$how_to_redeem_btn = '';
} elseif ($model->redeem_type == 1) {
	$using_click_class = '';
	$using_show_class = 'none';
	$using_scan_class = 'none';
	$how_to_redeem_btn = '<button class="btn btn-primary btn-small" rel="tipsy" title="'.BUtils::T('user_click_redeem_tips').'">'.BUtils::T('redeem_btn').'</button>';
} else {
	$using_scan_class = '';
	$using_click_class = 'none';
	$using_show_class = 'none';
	$how_to_redeem_btn = '<button class="btn btn-primary btn-small" rel="tipsy" title="'.BUtils::T('user_scan_redeem_tips').'">'.BUtils::T('scan_btn').'</button>';
}

//max number
$bar_max_number = ($model->max_number > 0) ? $model->max_number : 0;
$selected_max_num = $bar_max_number;
$special_term_max_number_msg = BUtils::T('offer_remaining_lbl', array('{number}' => '<span class="selected_max_num">'.$bar_max_number.'</span>'));

//offer content
$content = nl2br(strip_tags(trim($model->content)));

$start_date_ts = strtotime($model->start_date);
$end_date_ts = strtotime($model->end_date);
$selected_start_date = date('d.m.Y');
$selected_end_date = date('d.m.Y');
if ($start_date_ts > 0 and $end_date_ts > 0) {
	$selected_start_y = date('Y', $start_date_ts);
	$selected_start_m = date('m', $start_date_ts);
	$selected_start_d = date('d', $start_date_ts);
	$selected_start_date = date('d.m.Y', $start_date_ts);
	$selected_end_y = date('Y', $end_date_ts);
	$selected_end_m = date('m', $end_date_ts);
	$selected_end_d = date('d', $end_date_ts);
	$selected_end_date = date('d.m.Y', $end_date_ts);
	if ($selected_start_date === $selected_end_date) $selected_valid_date_html = $selected_start_date;
	else $selected_valid_date_html = $selected_start_date . ' - ' . $selected_end_date;
} else if ($start_date_ts > 0) {
	$selected_valid_date_html = date('d.m.Y', $start_date_ts);
	$selected_start_y = date('Y', $start_date_ts);
	$selected_start_m = date('m', $start_date_ts);
	$selected_start_d = date('d', $start_date_ts);
	$selected_start_date = date('d.m.Y', $start_date_ts);
	$selected_end_y = date('Y', $start_date_ts);
	$selected_end_m = date('m', $start_date_ts);
	$selected_end_d = date('d', $start_date_ts);
	$selected_end_date = date('d.m.Y', $start_date_ts);
} else if ($end_date_ts > 0) {
	$selected_valid_date_html = date('d.m.Y', $end_date_ts);
	$selected_start_y = date('Y', $end_date_ts);
	$selected_start_m = date('m', $end_date_ts);
	$selected_start_d = date('d', $end_date_ts);
	$selected_start_date = date('d.m.Y', $end_date_ts);
	$selected_end_y = date('Y', $end_date_ts);
	$selected_end_m = date('m', $end_date_ts);
	$selected_end_d = date('d', $end_date_ts);
	$selected_end_date = date('d.m.Y', $end_date_ts);
}
$valid_peroid = BUtils::GetDateRangeString(strtotime($selected_start_date), strtotime($selected_end_date));
?>
<div class="page-header position-relative">
	<h1>
		<?php echo $parentCaption; ?>
		<small>
			<i class="icon-double-angle-right"></i>
			<?php echo $caption; ?>
		</small>
	</h1>
</div><!--/.page-header-->

<div class="row-fluid">
	<div class="space-6"></div>
	
	<div class="row-fluid">
		<div class="span8">
			<div class="widget-box transparent">
				<div class="widget-header">
					<h4 class="lighter">
						<i class="icon-edit blue"></i> <?php echo $caption; ?>
					</h4>
				</div>
				<div class="widget-body">
					<div class="widget-main">

<div class="biz-form">
<?php
$form = $this->beginWidget('CActiveForm', array(
	'id'=>'special-form',
	'enableClientValidation'=>true,
	'clientOptions'=>array(
		'validateOnSubmit'=>true,
	),
));

//set the hidden input
echo $form->hiddenField($model, 'url_picture');
?>
<div class="fieldswrap">
<div class="fields">
	<div class="block" style="display:none !important;">
		<div class="lbl"><?php echo $form->labelEx($model,'id_merchant'); ?></div>
		<div class="ipt"><?php echo $form->textField($model,'id_merchant'); ?></div>
		<div class="spc"><?php echo $form->error($model,'id_merchant'); ?></div>
	</div>
	<div class="block">
		<div class="lbl"><?php echo $form->labelEx($model,'content'); ?></div>
		<div class="ipt"><?php echo $form->textArea($model,'content', array('class'=>'autosize-transition span12')); ?></div>
		<div class="eg hits"><?php echo BUtils::T('special_content_eg'); ?></div>
		<div class="spc"><?php echo $form->error($model,'content'); ?></div>
	</div>
</div>
<div class="fields">
	<div class="row-fluid">
		<div class="span6">
			<div class="lbl"><?php echo $form->labelEx($model,'price'); ?>: (€ 1234.50)</div>
			<div class="ipt">
				<label class="symbol">
					€ <?php echo $form->textField($model, 'price'); ?>
				</label>
			</div>
			<br />
			<div class="lbl"><?php echo $form->labelEx($model,'value'); ?>: (€ 1234.50)</div>
			<div class="ipt">
				<label class="symbol">
					€ <?php echo $form->textField($model, 'value'); ?>
				</label>
			</div>
		</div>
		<div class="span6 last right">
			<div class="lbl"><?php echo $form->labelEx($model,'discount'); ?></div>
			<div class="ipt">
				<label class="symbol">
					- <?php echo CHtml::textField('percent_discount', $discount_percent, array('class'=>'input-mini input-discount', 'maxlength'=>3)); ?>%
					<?php echo $form->hiddenField($model, 'discount'); ?>
				</label>
			</div>
		</div>
		<div class="spc"></div>
	</div>
</div>
<div class="fields">
	<div class="block">
		<div class="lbl">
			<label for="silder_max_number">
				<?php echo BUtils::T('special_max_number_lbl', array('{max_num}'=>'<span class="selected_max_num">'.$selected_max_num.'</span>')); ?>
			</label>
		</div>
		<div class="row-fluid">
			<div class="span6">
				<div class="ipt" style="margin-top:12px;">
					<div id="silder_max_number"></div>
					<?php echo $form->hiddenField($model,'max_number'); ?>
				</div>
			</div>
			<div class="span6 pull-right" style="margin-top:12px;">
				<div class="eg hits"><?php echo BUtils::T('special_max_number_eg'); ?></div>
			</div>
		</div>
	</div>
</div>
	<div class="fields">
	<div class="block">
		<div class="lbl"><label><?php echo BUtils::T('special_valid_time_lbl'); ?> <span class="required">*</span></label></div>
		<div class="row-fluid">
			<div class="span6">
				<div id="added-hours" class="added-hours"><?php echo $hours_list_op ?></div>
				<span class="tiny">
					<?php echo CHtml::dropDownList('weekday', 7, $aWeekDays, array('class'=>'weekday-op')); ?>
					<?php echo CHtml::dropDownList('hours-open', 9, $a24Hours, array('class'=>'hours-open-op')); ?>
					<?php echo CHtml::dropDownList('hours-close', 17, $a24Hours, array('class'=>'hours-close-op')); ?>
					<button class="btn btn-mini btn-blue add-hours" value="submit" type="button"><?php echo $add_hours_btn; ?></button>
				</span>
				<div class="clearfix"></div>
			</div>
			<div class="span6 pull-right">
				<div class="eg hits"><?php echo BUtils::T('special_valid_date_eg'); ?></div>
			</div>
		</div>
	</div>
</div>
<div class="fields">
	<div class="block">
		<div class="lbl"><label><?php echo BUtils::T('special_valid_date_lbl'); ?></label> (dd.mm.yyyy)</div>
		<div class="row-fluid">
			<div class="span12">
				<div class="input-prepend date">
					<span class="add-on">
						<i class="icon-calendar blue"></i>
					</span>
					<?php echo $form->textField($model, 'start_date', array('data-date-format'=>'dd.mm.yyyy', 'class'=>'date-picker', 'value'=>$selected_start_date)); ?>
				</div> - 
				<div class="input-append date">
					<?php echo $form->textField($model, 'end_date', array('data-date-format'=>'dd.mm.yyyy', 'class'=>'date-picker', 'value'=>$selected_end_date)); ?>
					<span class="add-on">
						<i class="icon-calendar blue"></i>
					</span>
				</div>
			</div>
			<div class="clear"></div>
		</div>
		<div class="eg hits"><?php echo BUtils::T('special_valid_date_eg'); ?></div>
		<div class="spc"></div>
	</div>
</div>
<?php if (false) { ?>
<div class="fields">
	<div class="block">
		<div class="lbl"><label><?php echo BUtils::T('how_to_redeem_lbl'); ?></label></div>
		<div class="ipt">
			<input type="radio" class="redeem_type" id="redeem_type_0" name="SpecialForm[redeem_type]" value="0" <?php echo ($model->redeem_type==0) ? 'checked="checked"':'' ?>/>
			<label for="redeem_type_0"><?php echo BUtils::T('special_using_scan_lbl'); ?></label>
			<span class="help-icon" rel="tipsy" title="The best precise: users can only redeem in your store."><img src="<?php echo Yii::app()->baseUrl; ?>/img/icons/hits.png" style="height:13px;" alt="?" /></span>
		</div>
		<div class="ipt">
			<input type="radio" class="redeem_type" id="redeem_type_1" name="SpecialForm[redeem_type]" value="1" <?php echo ($model->redeem_type==1) ? 'checked="checked"':'' ?>/>
			<label for="redeem_type_1"><?php echo BUtils::T('special_using_click_lbl'); ?></label>
			<span class="help-icon" rel="tipsy" title="High precise around 200m: some users might click near your store."><img src="<?php echo Yii::app()->baseUrl; ?>/img/icons/hits.png" style="height:13px;" alt="?" /></span>
		</div>
		<div class="ipt">
			<input type="radio" class="redeem_type" id="redeem_type_2" name="SpecialForm[redeem_type]" value="2" <?php echo ($model->redeem_type==2) ? 'checked="checked"':'' ?>/>
			<label for="redeem_type_2"><?php echo BUtils::T('special_using_show_lbl'); ?></label>
			<span class="help-icon" rel="tipsy" title="Low precise without any action."><img src="<?php echo Yii::app()->baseUrl; ?>/img/icons/hits.png" style="height:13px;" alt="?" /></span>
		</div>
		<div class="spc"></div>
	</div>
</div>
<?php } ?>
</div><!-- end of .fieldswrap -->

	<div class="margin actions">
		<?php echo CHtml::submitButton(BUtils::T('special_save_btn'), array('class' => 'btn btn-info btn-large')); ?>
		<?php echo CHtml::button(BUtils::T('cancel_btn'), array('class'=>'btn btn-link btn-large', 'onclick'=>'history.go(-1);', 'confirm'=>BUtils::T('cancel_btn_msg'))); ?>
	</div>
<?php $this->endWidget(); ?>
</div><!-- end of <div class="biz-form"> -->

					</div>
				</div>
			</div>
		</div><!-- end of <div class="span8"> -->
		
		<div class="span4">
			<div class="widget-box transparent">
				<div class="widget-header">
					<h4 class="lighter smaller">
						<i class="icon-eye-open blue"></i> <?php echo BUtils::T('preview_special_lbl'); ?>
					</h4>
				</div>
				<div class="widget-body">
					<div class="widget-main">
<div class="biz-form margin">
	<div class="eg"><?php echo BUtils::T('last_update_eg'); ?>: <span class="update-time"><?php echo $model->update_timestamp; ?></span></div>
	<div class="prepend-top append-bottom">
<style>
.qq-upload-button {
	font-size:11px; padding:2px 16px;
}
</style>
<div style="text-align:right;">
<?php $this->widget('ext.EAjaxUpload.EAjaxUpload', array(
	'id' => 'uploadOfferImage',
	'config' => array(
		'buttonName' => BUtils::T('upload_new_picture_eg'),
		'action' => Yii::app()->createUrl('/tools/offer/uploadOfferImage', array('id' => $model->id, 'mid' => $model->id_merchant)),
		'allowedExtensions'=>array("jpg","jpeg","gif","png"),
		'sizeLimit'=>8*1024*1024,
		'onComplete' => "js:function(id, fileName, responseJSON){ handleUploadedOffer(responseJSON); }",
	),
));
?>
</div>
<div class="offer_v2" style="width:auto;min-width:160px;max-width:380px;">
	<div class="offer-header relative">
		<img id="img_offer" src="<?php echo $url_picture; ?>" alt="" />
		<div class="info">
			<div class="mb_price">
				<div class="highlight" id="price-string"><?php echo $highlight; ?></div>
				<span id="value-string"><?php echo $del_price; ?></span>
			</div>
			<div class="mb_period">
				<div class="time" id="hour-range"><?php echo $range_time; ?></div>
				<div class="date"><?php echo $range_date; ?></div>
			</div>
			<div class="clearfix"></div>
		</div>
	</div>
	<div class="action">
		<div class="margin">
			<div id="redeem_type_0_view" class="<?php echo $using_scan_class; ?>">
				<div class="icon"><?php echo $using_scan_icon; ?></div>
				<div class="redeem_button"><?php echo $how_to_redeem_btn; ?></div>
				<div class="tips"><?php echo $using_scan_msg; ?></div>
			</div>
			<div id="redeem_type_1_view" class="<?php echo $using_click_class; ?>">
				<div class="icon"><?php echo $using_click_icon; ?></div>
				<div class="redeem_button"><?php echo $how_to_redeem_btn; ?></div>
				<div class="tips"><?php echo $using_click_msg; ?></div>
			</div>
			<div id="redeem_type_2_view" class="<?php echo $using_show_class; ?>">
				<div class="icon"><?php echo $using_show_icon; ?></div>
				<div class="redeem_button"><?php echo $how_to_redeem_btn; ?></div>
				<div class="tips"><?php echo $using_show_msg; ?></div>
			</div>
			<div class="clearfix"></div>
		</div>
	</div>
	<ul class="offer-detail">
		<li class="field clearfix">
			<i class="sign icon-time icon-2x"></i>
			<div class="desc">
				<span id="valid-time"><?php echo $hours_list; ?></span>
				<hr />
				<span id="valid-date"><?php echo $valid_peroid; ?></span>
			</div>
		</li>
		<li class="field clearfix">
			<i class="sign icon-map-marker icon-2x"></i>
			<div class="desc">
				<?php echo $biz_address; ?>
			</div>
		</li>
		<li class="field clearfix">
			<div id="special-content"><?php echo $content; ?></div>
		</li>
	</ul>
<?php
if ($bar_max_number == 0) {
	echo '<div class="remaining" style="display:none;">'.$special_term_max_number_msg.'</div>';
} else {
	echo '<div class="remaining">'.$special_term_max_number_msg.'</div>';
}
?>
</div>
	</div>
</div>
					</div>
				</div>
			</div>
		</div><!-- end of <div class="span8"> -->
		
	</div>
</div>
<script type="text/javascript">
$(function() {
	$('textarea[class*=autosize]').autosize({append: "\n"});
	
	//set redeem type real-time changes:
	$('.redeem_type').click(function(){
		var type = $(this).val();
		if (type == 2) {
			$('#redeem_type_0_view').hide();
			$('#redeem_type_1_view').hide();
			$('#redeem_type_2_view').show();
		} else if (type == 1) {
			$('#redeem_type_0_view').hide();
			$('#redeem_type_2_view').hide();
			$('#redeem_type_1_view').show();
		} else {
			$('#redeem_type_0_view').show();
			$('#redeem_type_1_view').hide();
			$('#redeem_type_2_view').hide();
		}
	});
	
	//real-time view: special content
	if ($('#SpecialForm_content').val() == "") {
		$('#special-content').hide();
	}
	$('#SpecialForm_content').keyup(function (event) {
		if ($('#SpecialForm_content').val() == "") {
			$('#special-content').hide();
		} else {
			$('#special-content').show();
		}
		$('#special-content').html(nl2br($(this).val()));
	});
	
	//real-time to calculate discount
	$('#SpecialForm_price, #SpecialForm_value').keyup(function() {
		var _price = get_price('#SpecialForm_price');
		var _value = get_price('#SpecialForm_value');
		var _discount = get_discount('#percent_discount')
		set_highlight(_price, _value, _discount);
	});
	$('#percent_discount').keyup(function() {
		get_discount('#percent_discount');
		var input = $('#percent_discount').val();
		if (input != '') {
			$('#price-string').html('<span class="euro">-'+$('#percent_discount').val()+'</span><span class="currency">%</span>');
		} else {
			$('#price-string').html('');
		}
	});
	
	//set the datepicker: the start date is tomorrow.
	//real-time view: valid date
	$('.date-picker').datepicker().on('changeDate', function(ev) {
		//var dayWrapper = moment(ev.date);
		//var start_string = dayWrapper.format('DD.MM.YYYY');
		//update the date string
		var start_date = $('#SpecialForm_start_date').val();
		var end_date = $('#SpecialForm_end_date').val();
		var date_string = '';
		if (start_date != '' && end_date != '') date_string = start_date + ' - ' + end_date;
		else if (start_date != '') date_string = start_date;
		else if (end_date != '') date_string = end_date;
		$('#valid-date').html(date_string);
	});
	
	//real-time view: special weekdays
	var week_days = <?php echo json_encode(array_values($aWeekDays)); ?>;
	$('#SpecialForm_week_days input[type="checkbox"]').bind('change', function () {
		var _week_days_string = '';
		$('#SpecialForm_week_days input[name="SpecialForm[week_days][]"]:checked').each(function (i) {
			var index = parseInt($(this).val());
			_week_days_string += week_days[index-1] + ' ';
		});
		$('#week-days').html(_week_days_string);
	});
	
	//real-time view: offer valid time
	$('.add-hours').click(function() {
		var weekday_op = $('.weekday-op option:selected');
		var weekday_next_op = weekday_op.next();
		var open_op = $('.hours-open-op option:selected');
		var close_op = $('.hours-close-op option:selected');
		var strHours = open_op.text() + ' - ' + close_op.text();
		var strValue = weekday_op.val() + ',' + open_op.val() + ',' + close_op.val();
		$('#added-hours').append('<div class="item">'
			+'<span class="weekday">'+weekday_op.text()+'</span> '
			+'<span class="hours">' + strHours + '</span> '
			+'<a href="javascript:;" class="remove-hours"><?php echo $delete_btn; ?></a>'
			+'<input type="hidden" value="' + strValue + '" name="offer_hours['+weekday_op.val()+']" />'
			+'</div>');
		$('.remove-hours').unbind('click').bind('click', function(){
			$(this).parent().remove();
		});
		//remove all, then select
		$('.weekday-op > option').attr('selected', false);
		weekday_next_op.attr('selected', true);
	});
	$('.remove-hours').unbind('click').bind('click', function(){
		$(this).parent().remove();
	});
	
	//real-time view: set max number : SpecialForm_max_number
	if ($("#SpecialForm_max_number").val() == "") {
		$('#selected_max_num_box').hide();//no value then hide
	}
	$("#silder_max_number").slider({
		range:"max", min:0, max:105, value:<?php echo $bar_max_number; ?>, step:5,
		slide: function(event, ui) {
			if (ui.value < 1 || ui.value > 100) {
				$('.remaining').hide();
				$("#SpecialForm_max_number").val('');
				$('.selected_max_num').html('<?php echo BUtils::T('special_max_num_unlimited_lbl'); ?>');
				$('#selected_max_num_box').hide();
			} else {
				$('.remaining').show();
				$("#SpecialForm_max_number").val(ui.value);
				$('#selected_max_num_box').show();
				$('.selected_max_num').html(ui.value);
			}
		}
	});
	
	//submit action
	$('#special-form').submit(function(){
		var _price = get_price('#SpecialForm_price');
		var _value = get_price('#SpecialForm_value');
		var _discount = get_discount('#percent_discount')
		set_highlight(_price, _value, _discount);
	});
});

//get amount
function get_price(eId) {
	var v = $(eId).val();
	if (v == '') return '';
	else return parseFloat(v);
}
//get discount
function get_discount(eId) {
	var v = $(eId).val();
	if (v == '') {
		$('#SpecialForm_discount').val('');
		return '';
	} else {
		var percent = parseInt(v);
		$('#SpecialForm_discount').val(percent / 100);
		return '';
	}
}
//
// discount = set_discount(10, 20, 50);
// -50
function set_highlight(price, value, pct_discount) {
	//calculate discount
	if (price != '' && price >= 0 && value != '' && value >= 0) {
		var _discount = 1 - price/value;
		$('#SpecialForm_discount').val(_discount);
		var _percent = Math.round(_discount * 100);
		$('#percent_discount').val(_percent);
	}
	if (price != '' && price >= 0) {
		$('#price-string').html('<span class="currency">&euro;</span><span class="euro">'+price+'</span>');
	} else if (pct_discount != '') {
		$('#price-string').html('<span class="euro">'+pct_discount+'</span>');
	}
	if (value != '' && value >= 0) {
		$('#value-string').html('<span class="oldprice label">&euro;'+value+'</span>');
	}
}

function handleUploadedOffer(respJSON) {
	if (respJSON.error) {
		$('.qq-upload-button').html('<span>'+respJSON.error+'</span>');
	} else {
		if (respJSON.url_offer_img) {
			$('#img_offer').attr('src', respJSON.url_offer_img);
			$('#SpecialForm_url_picture').val(respJSON.url_offer_img_db);
			$('ul.qq-upload-list').delay(1000).html('');
		}
	}
}
</script>